<!-- eslint-disable no-unused-vars -->
<template>
  <div>
    <div class="n-layout-page-header">
      <n-card :bordered="false" class="mt-4 proCard">
        <n-input-group>
          <n-input
            placeholder="请输入角色名称"
            :style="{ width: '300px' }"
            v-model:value="params.roleName"
          />
          <n-button type="info" @click="reloadTable()">
            <n-icon size="18"> <Search /> </n-icon> 搜索
          </n-button>
        </n-input-group>
      </n-card>
    </div>
    <n-card :bordered="false" class="mt-4 proCard">
      <BasicTable
        :columns="columns"
        :request="loadDataTable"
        :row-key="(row) => row.id"
        ref="actionRef"
        :actionColumn="actionColumn"
        @update:checked-row-keys="onCheckedRow"
      >
        <template #tableTitle>
          <n-button type="primary" @click="handleAdd">
            <template #icon>
              <n-icon>
                <PlusOutlined />
              </n-icon>
            </template>
            添加角色
          </n-button>
        </template>

        <template #action>
          <TableAction />
        </template>
      </BasicTable>
    </n-card>
    <n-drawer v-model:show="showModal" :width="502">
      <n-drawer-content>
        <template #header> {{ addRoleFlag ? '新增角色' : '编辑角色' }} </template>
        <template #footer>
          <n-button :loading="formBtnLoading" @click="confirmForm">提交</n-button>&nbsp;
          <n-button @click="resetForm">重置</n-button>
        </template>
        <n-spin :show="loadModal">
          <n-form
            ref="formRef"
            label-placement="left"
            label-width="auto"
            :model="roleFormState"
            :rules="roleFormRules"
          >
            <n-form-item label="角色编码" path="code">
              <n-input
                v-model:value="roleFormState.code"
                placeholder="输入角色编码"
                :disabled="!addRoleFlag"
              />
            </n-form-item>
            <n-form-item label="角色名称" path="name">
              <n-input v-model:value="roleFormState.name" placeholder="输入角色名" />
            </n-form-item>
            <n-form-item label="角色权限">
              <n-card size="medium">
                <n-tree
                  block-line
                  cascade
                  checkable
                  :virtual-scroll="true"
                  :data="treeData"
                  :checkedKeys="checkedKeys"
                  :expandedKeys="expandedKeys"
                  @update:checked-keys="selectedTree"
                  @update:expanded-keys="onExpandedKeys"
                  style="max-height: 650px; overflow: hidden"
                />
              </n-card>
            </n-form-item>
            <n-form-item label="备注">
              <n-input
                v-model:value="roleFormState.description"
                type="textarea"
                placeholder="请输入备注"
              />
            </n-form-item>
          </n-form>
        </n-spin>
      </n-drawer-content>
    </n-drawer>
  </div>
</template>

<script lang="ts" setup>
  import { reactive, ref, unref, h, onMounted } from 'vue';
  import { useMessage } from 'naive-ui';
  import { BasicTable, TableAction } from '@/components/Table';
  import { columns } from './columns';
  import { PlusOutlined } from '@vicons/antd';
  import { Search } from '@vicons/ionicons5';
  import {
    getRoleList,
    getRoleInfo,
    addRoleInfo,
    updateRoleInfo,
    deleteRoleInfo,
  } from '@/api/system/role';
  import { getAllPermission } from '@/api/system/permission';

  const message = useMessage();
  const actionRef = ref();
  const formRef: any = ref(null);
  const treeData = ref([]);
  let expandedKeys = ref([]);
  let checkedKeys = ref([]);
  const allPermissions = ref([] as any);

  const showModal = ref(false);
  const loadModal = ref(false);
  const formBtnLoading = ref(false);
  const addRoleFlag = ref(false);

  const params = reactive({
    pageSize: 10,
    roleName: '',
  });

  const actionColumn = reactive({
    width: 250,
    title: '操作',
    key: 'action',
    fixed: 'right',
    render(record) {
      return h(TableAction, {
        style: 'button',
        actions: [
          {
            label: '编辑',
            onClick: handleEdit.bind(null, record),
            ifShow: () => {
              return true;
            },
            auth: ['system_role_upd'],
          },
          {
            label: '删除',
            popConfirm: {
              title: '您确定要删除吗？',
              confirm: handleDelete.bind(null, record),
            },
            ifShow: () => {
              return true;
            },
            auth: ['system_role_del'],
          },
        ],
      });
    },
  });

  const roleFormState = reactive({
    roleId: undefined,
    name: '',
    code: '',
    description: '',
    permissions: [],
  });

  const roleFormRules = {
    name: { required: true, message: '请输入角色名称', trigger: 'blur' },
  };

  const loadDataTable = async (res: any) => {
    let _params = {
      ...unref(params),
      ...res,
    };
    return await getRoleList(_params);
  };

  function onCheckedRow(rowKeys: any[]) {
    console.log(rowKeys);
  }

  function resetForm() {
    formRef.value?.restoreValidation();
    roleFormState.roleId = undefined;
    roleFormState.name = '';
    roleFormState.code = '';
    roleFormState.description = '';
    roleFormState.permissions = [];
    treeData.value = getTreePermissions(allPermissions.value, []);
  }

  function reloadTable() {
    actionRef.value.reload();
  }

  function confirmForm(e: any) {
    e.preventDefault();
    formBtnLoading.value = true;
    formRef.value.validate(async (errors) => {
      if (!errors) {
        console.log(roleFormState);
        roleFormState.permissions = checkedKeys.value;
        if (addRoleFlag.value) {
          await addRoleInfo(roleFormState);
        } else {
          await updateRoleInfo(roleFormState);
        }
        message.success('保存成功');
        showModal.value = false;
        reloadTable();
      } else {
        message.error('请填写完整信息');
      }
      formBtnLoading.value = false;
    });
  }

  async function handleAdd() {
    console.log('点击了新增');
    showModal.value = true;
    addRoleFlag.value = true;
    // 重置表单
    resetForm();
  }

  async function handleEdit(record: Recordable) {
    console.log('点击了编辑', record);
    showModal.value = true;
    loadModal.value = true;
    addRoleFlag.value = false;
    const roleInfo = await getRoleInfo(record.id);
    console.log(roleInfo);
    roleFormState.roleId = roleInfo.roleId;
    roleFormState.name = roleInfo.roleName;
    roleFormState.code = roleInfo.roleCode;
    roleFormState.description = roleInfo.description;
    treeData.value = getTreePermissions(allPermissions.value, roleInfo.permissions);
    loadModal.value = false;
  }

  async function handleDelete(record: Recordable) {
    console.log('点击了删除', record);
    await deleteRoleInfo(record.id);
    message.success('删除成功');
    reloadTable();
  }

  onMounted(async () => {
    allPermissions.value = await getAllPermission();
  });

  function getTreePermissions(permissions, checkedPermissions) {
    return permissions.map((item) => {
      if (checkedPermissions.indexOf(item.name) >= 0) {
        checkedKeys.value.push(item.name as never);
      }
      const children = item.children ? getTreePermissions(item.children, checkedPermissions) : [];
      return {
        key: item.name,
        label: item.title,
        children: children,
        isLeaf: children.length == 0,
      };
    });
  }

  function selectedTree(keys) {
    checkedKeys.value = keys;
  }

  function onExpandedKeys(keys) {
    expandedKeys.value = keys;
  }
</script>

<style lang="less" scoped></style>
